package com.zzyl.nursing.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.MemberDataDayDto;
import com.zzyl.nursing.dto.UserDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    static List<String> DEFAULT_NICK_NAME = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if (ObjectUtil.isEmpty(familyMember)) {
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder()
                    .openId(openid)
                    .build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember, phone);

        //6. 把用户的信息封装到token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", familyMember.getName());
        claims.put("userId", familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    /**
     * 查询所有家庭成员
    * */
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Override
    public List<MemberElderVo> listMemberElder() {
        ArrayList<MemberElderVo> vos = new ArrayList<>();
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(new LambdaQueryWrapper<FamilyMemberElder>()
                .eq(FamilyMemberElder::getFamilyMemberId, userId));
        // 循环
        familyMemberElders.forEach(familyMemberElder -> {
            MemberElderVo vo = new MemberElderVo();
            BeanUtil.copyProperties(familyMemberElder, vo);
            vo.setElderName(elderMapper.selectById(familyMemberElder.getElderId()).getName());
            vos.add(vo);
        });
        return vos;
    }

    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Override
    public List<ElderMemberDetailVo> selectElderList() {
        ArrayList<ElderMemberDetailVo> vos = new ArrayList<>();
        // 根据当前用户id查询中间表中数据
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(
                new LambdaQueryWrapper<FamilyMemberElder>().eq(FamilyMemberElder::getFamilyMemberId, userId));
        // 挨个查询老人数据
        familyMemberElders.forEach(familyMemberElder -> {
            ElderMemberDetailVo vo = new ElderMemberDetailVo();
            vo.setMid(String.valueOf(familyMemberElder.getId())); // Convert Long to String
            vo.setMremark(familyMemberElder.getRemark());
            vo.setElderId(String.valueOf(familyMemberElder.getElderId()));
            // 根据老人id查询
            Elder elder = elderMapper.selectById(familyMemberElder.getElderId());
            vo.setName(elder.getName());
            vo.setImage(elder.getImage());
            vo.setBedNumber(elder.getBedNumber());
            // 根据bedId查询房间id==>房间类型
            Long roomId = bedMapper.selectById(elder.getBedId()).getRoomId();
            vo.setTypeName(roomMapper.selectRoomById(roomId).getTypeName());
            // 根据老人id查询设备==>locationType=0==>physical_location_type=-1==>binding_location是用户id
            LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<Device>().eq(Device::getLocationType, 0).eq(Device::getPhysicalLocationType, -1)
                    .eq(Device::getBindingLocation, familyMemberElder.getElderId());
            // 正确的做法
            List<Device> devices = deviceMapper.selectList(queryWrapper);
            if (devices != null && !devices.isEmpty()) {
                // 你可以选择第一个，或者遍历处理
                Device firstDevice = devices.get(0);
                vo.setIotId(firstDevice.getIotId());
                vo.setDeviceName(firstDevice.getDeviceName());
                vo.setProductKey(firstDevice.getProductKey());
            }
            vos.add(vo);
        });
        return vos;
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public List<MemberPropertiesDataVo> queryServiceProperties(String iotId) {
        List<MemberPropertiesDataVo> list = new ArrayList<>();
        String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        if (StringUtils.isEmpty(jsonStr)) {
            throw new RuntimeException("数据不存在");
        }
        List<DeviceData> deviceDataAll = JSONUtil.toList(jsonStr, DeviceData.class);
        deviceDataAll.forEach(deviceData -> {
            MemberPropertiesDataVo vo = new MemberPropertiesDataVo();
            vo.setFunctionId(deviceData.getFunctionId());
            vo.setEventTime(String.valueOf(deviceData.getAlarmTime()));
            vo.setValue((int) Double.parseDouble(deviceData.getDataValue()));
            list.add(vo);
        });
        return list;
    }

    @Autowired
    private DeviceDataMapper deviceDataMapper;
    /**
     * 根据四个参数获取格式化后的数据
     * @param functionId 功能ID
     * @param startTime 开始时间（毫秒）
     * @param endTime 结束时间（毫秒）
     * @param iotId 设备ID
     * @return 格式化后的时间和数据值列表
     */
    @Override
    public List<MemberDataDayVo> queryDeviceDataListByDay(MemberDataDayDto dto) {
        // 只包含每个小时最先记录的数据
        List<MemberDataDayVo> deviceDataList = deviceDataMapper.selectByHour(dto);

        // 2. 转换时间范围为LocalDateTime（毫秒转秒）
        LocalDateTime start = LocalDateTime.ofEpochSecond(dto.getStartTime() / 1000, 0, ZoneOffset.of("+8"));
        LocalDateTime end = LocalDateTime.ofEpochSecond(dto.getEndTime() / 1000, 0, ZoneOffset.of("+8"));

        // 3. 生成时间范围内的所有整点（如00:00、01:00...）
        List<LocalDateTime> allHours = new ArrayList<>();
        // 截断到小时（如00:23→00:00）
        LocalDateTime current = start.truncatedTo(ChronoUnit.HOURS);
        while (!current.isAfter(end)) {
            allHours.add(current);
            // 加1小时
            current = current.plusHours(1);
        }
        // 4. 将数据库查询结果转为Map（key：小时时间，value：数据值）
        // 原始时间字符串的格式（如yyyy-MM-dd HH:mm:ss）
        DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 目标格式（HH:mm）
        DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("HH:mm");
        Map<String, BigDecimal> hourDataMap = deviceDataList.stream()
                .collect(Collectors.toMap(
                        // MemberDataDayVo::getDateTime,
                        vo -> LocalDateTime.parse(vo.getDateTime(), originalFormatter)
                                .format(targetFormatter),
                        MemberDataDayVo::getDataValue
                ));
        // 5. 补全所有整点数据（有数据用查询值，无数据用默认值）
        return allHours.stream()
                .map(hour -> {
                    String timeStr = hour.format(DateTimeFormatter.ofPattern("HH:mm"));
                    BigDecimal dataValue = hourDataMap.getOrDefault(timeStr, BigDecimal.valueOf(0.0));

                    return new MemberDataDayVo(timeStr, dataValue);

                }).collect(Collectors.toList());
    }

    @Override
    public List<MemberDataDayVo> queryDeviceDataListByWeek(MemberDataDayDto dto) {
        // 只包含每个小时最先记录的数据
        List<MemberDataDayVo> deviceDataList = deviceDataMapper.selectByDay(dto);

        // 2. 转换时间范围为LocalDateTime（毫秒转秒）
        LocalDateTime start = LocalDateTime.ofEpochSecond(dto.getStartTime() / 1000, 0, ZoneOffset.of("+8"));
        LocalDateTime end = LocalDateTime.ofEpochSecond(dto.getEndTime() / 1000, 0, ZoneOffset.of("+8"));

        // 创建格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.dd");

        // 3. 使用 Stream API 生成日期列表
        List<String> allMonthDays = Stream.iterate(start, date -> date.plusDays(1))
                .limit(start.until(end, java.time.temporal.ChronoUnit.DAYS) + 1)
                .map(date -> date.format(formatter))
                .collect(Collectors.toList());
        // 4. 将数据库查询结果转为Map（key：日期MM.dd，value：数据值）
        Map<String, BigDecimal> dayDataMap = deviceDataList.stream()
                .collect(Collectors.toMap(
                        MemberDataDayVo::getDateTime,
                        MemberDataDayVo::getDataValue
                ));
        // 5. 补全所有整点数据（有数据用查询值，无数据用默认值）
        return allMonthDays.stream()
                .map(day -> {
                    BigDecimal dataValue = dayDataMap.getOrDefault(day, BigDecimal.valueOf(0.0));
                    return new MemberDataDayVo(day, dataValue);
                }).collect(Collectors.toList());
    }

    /**
     * 新增或修改用户
     *
     * @param familyMember
     * @param phone
     */
    private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //1. 判断新的手机跟数据库中保存的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }

        //2. id是否存在，如存在，就修改
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }

        //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
        int index = (int) (Math.random() * DEFAULT_NICK_NAME.size());
        String nickName = DEFAULT_NICK_NAME.get(index) + phone.substring(phone.length() - 4);
        familyMember.setName(nickName);
        save(familyMember);

    }

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */

    @Autowired
    private ElderMapper elderMapper;

    @Override
    public int insertFamilyMember(UserDto dto) {
        // 新增老人与家属的中间关系
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setRemark(dto.getRemark());
        // 根据老人的身份证号和姓名查询老人id
        String idCard = dto.getIdCard();
        String name = dto.getName();
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, idCard).eq(Elder::getName, name));
        if (elder == null) {
            throw new RuntimeException("没有该老人");
        }
        familyMemberElder.setElderId(elder.getId());
        // 查询家人id
        Long userId = UserThreadLocal.getUserId();
        if (userId == null) {
            throw new RuntimeException("请登录");
        }
        familyMemberElder.setFamilyMemberId(userId);

        int inserted = familyMemberElderMapper.insert(familyMemberElder);
        return inserted == 0 ? 0 : 1;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
